import { checkLoginAndNavigate, Toast } from '@/utils/util';

// 后端返回的通用响应结构
export type ResponseData<T> = {
  code: number;
  msg: string;
  data: T;
  time: string;
};

// resolve和reject不返回任何值，但通知promise更改状态
const handleResponse = <T>(res: any, resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => {
  // 分离了验证状态码逻辑
  if (isSuccessStatusCode(res.statusCode)) {
    if (res.data.code == 1) {
      resolve(res.data);
    } else if (res.data.code == -1) {
      // 登录失败
      uni.removeStorageSync('token');
      // 使用统一的登录检查函数，避免重复跳转
      checkLoginAndNavigate();
      reject(res.data);
    } else if (res.data.code == -5) {
      uni.showModal({
        title: '提示',
        content: res.data?.msg || '报名前请先注册并登录“古城润物无声”小程序',
        success: c => {
          if (c.confirm) {
            // 获取用户失败，跳转润无声小程序
            uni.navigateToMiniProgram({
              appId: res.data.data?.xcx_appid || '',
              path: res.data.data?.rwws_xcx_page || 'page/index/index',
              // extraData: {
              //   foo: "bar",
              // },
              envVersion: 'release',
              success(res) {
                // 打开成功
                console.log('跳转润无声小程序：', res);
              },
            });
          }
        },
      });
      reject(res.data);
    } else {
      showErrorToast(res.data);
      reject(res.data);
    }
  } else {
    // 分离了报错状态码逻辑
    showErrorToast(res.data);
    reject(res);
  }
};

const handleError = (err: any, reject: (reason?: any) => void) => {
  Toast('网络可能开小差了~');
  reject(err);
};

const isSuccessStatusCode = (statusCode: number) => {
  return statusCode >= 200 && statusCode < 300;
};

const showErrorToast = <T>(data: ResponseData<T>) => {
  Toast(data.msg || '请求错误');
};

const request = <T>(
  url: string,
  method: 'GET' | 'POST',
  data?: string | AnyObject | ArrayBuffer
): Promise<ResponseData<T>> => {
  return new Promise((reslove, reject) => {
    uni.request({
      url: process.env.VUE_APP_BASEHOST + url,
      header: {
        Authorization: uni.getStorageSync('token'),
      },
      method,
      data,
      success: res => {
        // 成功响应
        handleResponse(res, reslove, reject);
      },
      fail: err => {
        handleError(err, reject);
      },
    });
  });
};

// 上传图片
export const uploadRequest = <T>(
  url: string,
  filePath: string,
  formData?: Record<string, any>
): Promise<ResponseData<T>> =>
  new Promise((reslove, reject) => {
    uni.uploadFile({
      url: process.env.VUE_APP_BASEHOST + url,
      header: {
        Authorization: uni.getStorageSync('token'),
      },
      filePath,
      name: 'file',
      formData,
      success: res => {
        // console.log(res);
        if (res?.statusCode !== 200) {
          Toast('上传失败，请稍后重试');
          return reject(res);
        }
        res.data = JSON.parse(res.data);
        handleResponse(res, reslove, reject);
      },
      fail: err => {
        console.error(err);
        reject(err);
      },
    });
  });

export default request;
